package astra.client.utils.dialogs;

import astra.client.Astra;
import astra.client.models.Employee;
import astra.client.services.AstraServiceAsync;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;

/**
 * @author Kotelnikov Dmitry <a href="mailto:dimonnot@mail.ru"/>
 */
public class AuthDialog extends DialogBox {
    interface AuthDialogUiBinder extends UiBinder<HTMLPanel, AuthDialog> {
    }

    private static AuthDialogUiBinder ourUiBinder = GWT.create(AuthDialogUiBinder.class);

    @UiField
    TextBox username;

    @UiField
    PasswordTextBox password;

    @UiField
    Button signIn;
    @UiField
    SimplePanel message;

    private AstraServiceAsync service;
    private Astra client;

    public AuthDialog(AstraServiceAsync service, Astra client) {
        super(false, true);
        setGlassEnabled(true);
        this.service = service;
        this.client = client;
        setText("Авторизация");
        add(ourUiBinder.createAndBindUi(this));
    }

    @UiHandler("signIn")
	void onClick(ClickEvent e) {
        signIn.setEnabled(false);
        service.signIn(username.getValue(), password.getValue(), new AsyncCallback<Employee>() {
            @Override
            public void onFailure(Throwable caught) {
                signIn.setEnabled(true);
                Window.alert(caught.getMessage());
            }

            @Override
            public void onSuccess(Employee result) {
                signIn.setEnabled(true);
                client.onSuccess(result);
            }
        });
	}

    public SimplePanel getMessage() {
        return message;
    }
}